var form = layui.form,
    id=getQueryVariable("id"),
    type=getQueryVariable("type"),
    laydate = layui.laydate,
    upload = layui.upload,
    table = layui.table,
    $ = layui.jquery,
    layer = layui.layer
;
//附件集合
let annexData = [];

function getAllJson(jsons) {
    let tmpitem=[]
    for (let item of jsons) {
        let tmparr={}
        tmparr["value"]=item["code"];
        tmparr["name"]=item["name"];
        if(item["users"]){
            for(let it of item["users"]){
                //接收人不包含自己
                if (it.code!=user.code){
                    item["list"].push(it)
                }
            }
        }
        if(item["list"] && item["list"].length){
            tmparr["children"]=   getAllJson(item["list"]);
            tmpitem.push(tmparr)
        }else{
            tmpitem.push(tmparr)
        }

    }
    return tmpitem
}

function getxmselect(el,name, data) {
    return xmSelect.render({
        el: el,
        name: name,
        tree: {
            show: true,
            showLine: true,
            showFolderIcon:true,
            indent: 20,
            expandedKeys:false
        },
        height: '500px',
        data: data,
        on: function ({ arr, change, isAdd }) {
            return this
        }
    })
}
var receiverCodeList=[];
layer.ready(function () {
    //获取当前用户的部门及人员结构树
    let treeList = getCurrentDepartmentUser();
    if (treeList && treeList.list) {
        let userTree = getAllJson(treeList.list);
        receiverCodeList= getxmselect("#receiverCode", "receiverCode", userTree);
    } else {
        receiverCodeList= getxmselect("#receiverCode", "receiverCode", [{name: user.name, value: user.code}])
    }
})




//表单初始值，修改时调用
if(id!=""){
    var obj=queryByid();
    form.val("announcement-form",{
        "theme":obj.theme,
        "content":obj.content,
        "publisherCode":obj.publisherCode,
        "publisherName":obj.publisherName,
    })
}else {
    form.val("announcement-form",{
        "publisherCode":user.code,
        "publisherName":user.name,
    })
}

//---附件
table.render({
    elem: '#attachment'
    , toolbar: '#attachmenttoolbar'
    , data:annexData
    , cols: [[
        {field: 'numbers',width: 50,type:'numbers',title:'序号'}
        , {field: 'fileName', title: '文件名', fixed: true,event: "fileName"}
        , {field: 'uploadTime', title: '上传日期', fixed: true}
        , {fixed: 'right', width: 180, align: 'center', toolbar: '#attachmenteditor', title: '操作'}
    ]]
    , id: 'attachmenttableid'
    , height: 380
    ,page: false
    ,limit: Number.MAX_VALUE
});
let uploadListIns = upload.render({
    elem: '#uploadfile'
    , url: 'transfer/uploadFile'
    , field: "uploadify"
    , accept: 'file'
    , multiple: true
    , auto: false
    , bindAction: '#testListAction'
    , choose: function (obj) {
        var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
        //读取本地文件
        obj.preview(function (index, file, result) {
            var tr = $(['<tr id="upload-' + index + '">'
                , '<td>' + file.name + '</td>'
                , '<td>' + (file.size / 1024).toFixed(1) + 'kb</td>'
                , '<td>等待上传</td>'
                , '<td>'
                , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                , '</td>'
                , '</tr>'].join(''));

            //单个重传
            tr.find('.demo-reload').on('click', function () {
                obj.upload(index, file);
            });

            //删除
            tr.find('.demo-delete').on('click', function () {
                delete files[index]; //删除对应的文件
                tr.remove();
                uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
            });

            $("#uploadlist").append(tr);
        });
    }
    , parseData: function(res){
        return {
            "code": res.status,
            "count": res.total,
            "data": res.data
        };
    }
    , done: function (res, index, upload) {
        let data = res.data;
        for(var i in data){
            if (data[i].status) { //上传成功
                data[i].fileUrl=res.data[i].ftpPath+"/"+res.data[i].fileName;
                annexData.push(data[i]);
                var tr = $("#uploadlist").find('tr#upload-' + index)
                    , tds = tr.children();
                tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                tds.eq(3).html(''); //清空操作
                return delete this.files[index]; //删除文件队列已经上传成功的文件
            }
            this.error(index, upload);
        }
    }
    , error: function (index, upload) {
        var tr = $("#uploadlist").find('tr#upload-' + index)
            , tds = tr.children();
        tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
        tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
    }
});

table.on('toolbar(attachmenttable)', function (obj) {
    var checkStatus = table.checkStatus(obj.config.id);
    switch (obj.event) {
        case 'uploadfile':
            $("#uploadlist").html(""); //清空上传列表数据
            layer.open({
                type: 1,
                title: "文件上传",
                area: ['710px', '340px'],
                content: $("#attachmentupload")//引用的弹出层的页面层的方式加载修改界面表单
                , cancel: function (index, layero) {
                    table.reload('attachmenttableid', {data:annexData}); //点击关闭刷新表格
                }
            });
            break;
    }
    ;
});
table.on('tool(attachmenttable)', function (obj) {
    let data = obj.data;
    if (obj.event === 'download') { //下载
        let xmlHttpRequest = new XMLHttpRequest();
        let url = "wjinfo/downloadfile2?filename=" + data.filePath;
        xmlHttpRequest.open('GET', url, true);
        //设置请求头
        xmlHttpRequest.setRequestHeader("Content-type", "application/json")
        xmlHttpRequest.responseType = "blob";
        xmlHttpRequest.send(null);

        xmlHttpRequest.onload = function() {
            let content = xmlHttpRequest.response;
            // 组装a标签
            let elink = document.createElement("a");

            //设置文件下载路径
            elink.download = decodeURIComponent(data.fileName);
            elink.style.display = "none";
            let blob = new Blob([content], { type: 'application/force-download' });

            //解决下载不存在文件的问题，根据blob大小判断
            if(blob.size==0){
                layer.msg('服务器没找到此文件，请联系管理员!');
            }else{
                elink.href = window.URL.createObjectURL(blob);
                document.body.appendChild(elink);
                elink.click();
                document.body.removeChild(elink);
            }

        }
    } else if (obj.event === 'del') {
        layer.confirm('确认删除?',
            confirmInfo(3,5), function (index) {
                obj.del();
                var id = data.id;
                for (var i = 0; i < annexData.length; i++) {
                    if (annexData[i].id == id) {
                        annexData.splice(i, 1); // 将使后面的元素依次前移，数组长度减1
                        i--; // 如果不减，将漏掉一个元素
                        break;
                    }
                }
                layer.msg("删除成功", {icon: 6});
                layer.close(index);
                table.reload('attachmenttableid', {data:annexData}); //ajax删除成功之后刷新表格
            });
    }else if(obj.event === 'fileName'){//点击名称，在线预览
        onLineFile(obj.data.fileUrl);
    }
});

//提示信息渲染
function confirmInfo(icon, anim) {
    let data = {
        icon: icon,
        title: "提示",
        offset: "auto",
        skin: 'layui-layer-molv',
        anim: anim
    }
    return data;
}





//监听提交
form.on('submit(form-element)', function(data){
    //追加当前登录人,接收人也有自己
    if(data.field.receiverCode=="" || data.field.receiverCode==null){
        data.field.receiverCode=user.code;
    }else{
        data.field.receiverCode=data.field.receiverCode+","+user.code
    }

    let req = data.field;
    //获取附件数据
    req["annexList"] = table.cache["attachmenttableid"];

    if(saveMessage(req)){
        layer.msg("保存成功", {icon: 6});
        setTimeout(function () {
            //保存成功则刷新提交过来的界面 并关闭此页面
            parent.detab("views/jsp/BasicData/message.jsp","消息");
            parent.intab("views/jsp/BasicData/message.jsp","消息")
            parent.detab("views/jsp/BasicData/tpl/newupannouncement.jsp?type=2","新增发布公告");
            parent.detab("views/jsp/BasicData/tpl/newupannouncement.jsp?id="+id+"&type=2","修改发布公告");
        },1000)
    }else{
        layer.msg("保存失败", {icon: 6});
    }

    return false;
});

function queryByid() {
    var obj=[];
    $.ajax({
        type : 'get',
        data:{"id":id},
        url:'message/queryByid',
        dataType:"json",
        async:false,
        success : function (da) {
            if(da.status==200 ){
                obj=da.data;
                let receiverCodeArray=da.data.receiverCode.split(",");
                receiverCodeList.setValue(receiverCodeArray);
                annexData=da.data.annexList;
            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });
    return obj;
}
function saveMessage(data) {
    data.messageType=type;
    if(id !="") data.id=id;
    var tf=false;
    $.ajax({
        type : 'post',
        data:JSON.stringify(data),
        url:'message/saveMessage',
        dataType:"json",
        contentType: 'application/json',
        async:false,
        success : function (da) {
            if(da.status==200 ){
                tf=true;
            }
        }
    });
    return tf;
}